import React, { Component } from 'react';
import PubSub from 'pubsub-js';
// import axios from 'axios';
export default class Search extends Component {
  searchUsers = async (event) => {
    if (event.key === 'Enter' || event.type === 'click') {
      // 阻止默认行为，防止提交表单
      event.preventDefault();
      // 获取用户输入(连续解构赋值+重命名)
      const {
        keywordElement: { value: keyword },
      } = this;
      // 发送请求前通知List更新状态
      PubSub.publish('search_user', { isFirst: false, isLoading: true });
      // axios发送请求
      // axios.get(`/api/search/users2?q=${keyword}`).then(
      //   (response) => {
      //     // 请求成功后通知List更新状态
      //     PubSub.publish('search_user', {
      //       isLoading: false,
      //       users: response.data.items,
      //     });
      //   },
      //   (error) => {
      //     // 请求失败后通知List更新状态
      //     PubSub.publish('search_user', {
      //       isLoading: false,
      //       err: error.message,
      //     });
      //   }
      // );
      //

      // fetch发送请求(优化后【async/await】)
      try {
        const response = await fetch(`/api/search/users2?q=${keyword}`);
        const data = await response.json();
        PubSub.publish('search_user', {
          isLoading: false,
          users: data.items,
        });
      } catch (error) {
        PubSub.publish('search_user', {
          isLoading: false,
          err: error.message,
        });
      }
    }
  };
  render() {
    return (
      <section className='jumbotron' style={{ padding: '20px' }}>
        <h3 className='jumbotron-head'>搜索Github用户</h3>
        <div>
          <input
            type='text'
            ref={(c) => (this.keywordElement = c)}
            placeholder='输入关键字进行搜索'
            onKeyDown={this.searchUsers}
          />
          &nbsp;
          <button onClick={this.searchUsers}>搜索</button>
        </div>
      </section>
    );
  }
}
